package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.common.contants.MQConstants;
import com.heima.common.contants.RedisConstants;
import com.heima.common.dtos.AppHttpCodeEnum;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.exception.LeadNewsException;
import com.heima.model.article.dtos.UpdateArticleMsg;
import com.heima.model.behavior.dtos.ArticleUserInfoDto;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.JsonUtils;
import com.heima.utils.common.ThreadLocalUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.common.protocol.types.Field;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Override
    public ResponseResult likesBehavior(LikesBehaviorDto dto) {
        //参数校验
        if(dto.getArticleId()==null || dto.getType()==null || dto.getOperation()==null){
            throw new LeadNewsException(AppHttpCodeEnum.PARAM_INVALID);
        }

        //判断用户是否登录
        ApUser apUser = (ApUser)ThreadLocalUtils.get();
        if(apUser==null) {
            throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
        }

        //判断是否为点赞或取消点赞
        if(dto.getOperation().equals((short)0)){
            //点赞
            //判断用户是否点赞过
            Object o = redisTemplate.opsForHash().get(RedisConstants.LIKE_BEHAVIOR+dto.getArticleId().toString(), apUser.getId().toString());
            if(o!=null){
                throw new LeadNewsException(400,"你已经点赞过，无需重复操作");
            }

            //存储点赞数据
            /**
             * 参数一：第一个Map的key
             * 参数二：第二个Map的key
             * 参数二：第二个Map的value
             */
            redisTemplate.opsForHash().put(RedisConstants.LIKE_BEHAVIOR+dto.getArticleId().toString(),apUser.getId().toString(), JsonUtils.toString(dto));

            //发送消息给KafkaStream进行数据同步
            UpdateArticleMsg articleMsg = new UpdateArticleMsg();
            articleMsg.setArticleId(dto.getArticleId());
            articleMsg.setType(UpdateArticleMsg.UpdateArticleType.LIKES);
            kafkaTemplate.send(MQConstants.HOT_ARTICLE_INPUT_TOPIC,JsonUtils.toString(articleMsg));

        }else{
            //取消点赞
            redisTemplate.opsForHash().delete(RedisConstants.LIKE_BEHAVIOR+dto.getArticleId().toString(),apUser.getId().toString());
        }


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    //文章 不喜欢/取消不喜欢
    @Override
    public ResponseResult unLikesBehavior(UnLikesBehaviorDto dto) {
        try {
            //判断是否登录
            ApUser user = (ApUser) ThreadLocalUtils.get();
            if (user == null){
                throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
            }

            //校验参数
            if (dto.getArticleId() == null){
                throw new LeadNewsException(AppHttpCodeEnum.PARAM_REQUIRE);
            }
            //存入或删除redis中数据
            String key = RedisConstants.ARTICLE_LIKE_UNLIKE+dto.getArticleId().toString();
//            String articleUnlike = redisTemplate.opsForValue().get(key);
            Object o = redisTemplate.opsForHash().get(key, user.getId().toString());
            if (dto.getType()== 0){
                //不喜欢
                if (o != null){
                    //已经存在
                    return ResponseResult.okResult("你已经设置为不喜欢，无需再操作");
                }

                //存入
                //存储点赞数据
                /**
                 * 参数一：第一个Map的key
                 * 参数二：第二个Map的key
                 * 参数二：第二个Map的value
                 */
                redisTemplate.opsForHash().put(key,user.getId().toString(),JsonUtils.toString(dto));

                return ResponseResult.okResult(null);
            }{
                //取消不喜欢
                if (o == null){
                    //已经存在
                    return ResponseResult.okResult("你没有设置为不喜欢，无需再操作");
                }
                //删除数据
                redisTemplate.opsForHash().delete(key,user.getId().toString());
                return ResponseResult.okResult(null);
            }

        } finally {
            ThreadLocalUtils.remove();
        }
    }

    //查看文章是否点赞  自己调用
    @Override
    public boolean islike(ArticleUserInfoDto dto) {
        boolean flag= false;

        String key=RedisConstants.LIKE_BEHAVIOR+dto.getArticleId();
        String apUserId = dto.getUserId().toString();

        Object o = redisTemplate.opsForHash().get(key, apUserId);
        if (o != null){
            return flag=true;
        }
        return flag;
    }

    //查看文章 不喜欢/取消不喜欢 状态  自己调用
    @Override
    public boolean isunlike(ArticleUserInfoDto dto) {

        boolean flag= false;

        String key=RedisConstants.ARTICLE_LIKE_UNLIKE+dto.getArticleId();
        String apUserId = dto.getUserId().toString();

        Object o = redisTemplate.opsForHash().get(key, apUserId);
        if (o != null){
            return flag=true;
        }
        return flag;

    }

    @Override
    public Map<String, Boolean> islikeAndisunlike(ArticleUserInfoDto dto) {

        boolean islike = this.islike(dto);
        boolean isunlike = this.isunlike(dto);

        Map<String,Boolean> map = new HashedMap();
        map.put("islike",islike);
        map.put("isunlike",isunlike);

        return map;
    }
}
